package com.yhzl.two.shop.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yhzl.two.shop.common.OrderState;
import com.yhzl.two.shop.common.ServerResponse;
import com.yhzl.two.shop.entity.Order;
import com.yhzl.two.shop.entity.OrderItem;
import com.yhzl.two.shop.mapper.OrderItemMapper;
import com.yhzl.two.shop.mapper.OrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

@Service
public class AliService {

    private final OrderItemMapper orderItemMapper;
    private final OrderMapper orderMapper;

    private static final Logger logger = LoggerFactory.getLogger(AliService.class);
    private static final String TIMEOUT_EXPRESS = "90m";
    private static final String STORE_ID = "NJ_001";

    @Autowired
    public AliService(OrderItemMapper orderItemMapper, OrderMapper orderMapper) {
        this.orderItemMapper = orderItemMapper;
        this.orderMapper = orderMapper;
    }

    /**
     * 支付宝预下单接口，可获取支付地址，前端将支付地址转换为二维码，以便用户扫码支付
     *
     * @param oid 订单id
     * @param uid 用户id
     * @return 二维码地址
     */
    public ServerResponse<String> alipayTradePagePayService(String oid, Integer uid) {
        List<OrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("oid", oid));
        if (orderItems == null) {
            return ServerResponse.createErrorMessage("非法操作");
        }
        BigDecimal sumPrice = BigDecimal.valueOf(0);
        for (OrderItem v : orderItems) {
            sumPrice = sumPrice.add(v.getPrice().multiply(BigDecimal.valueOf(v.getNum())));
        }
        AlipayClient alipayClient = AliService.getAlipayClient();
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); //创建API对应的request类
        Map<String, Object> params = new HashMap<>();
        params.put("out_trade_no", oid);
        params.put("timeout_express", TIMEOUT_EXPRESS);
        params.put("store_id", STORE_ID);
        params.put("total_amount", sumPrice.doubleValue());
        params.put("subject", orderItems.get(0).getName());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            request.setBizContent(objectMapper.writeValueAsString(params));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        AlipayTradePrecreateResponse response = null; //通过alipayClient调用API，获得对应的response类
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ServerResponse.createSuccessMessage(response.getQrCode());
    }

    /**
     * 退款接口
     * @param oid 订单id
     * @return  退款信息
     */
    public AlipayTradeRefundResponse alipayTradeRefundService(String oid) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("oid", oid));
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        Map<String, Object> params = new HashMap<>();
        params.put("out_trade_no", oid);
        params.put("refund_amount", order.getSumPrice().doubleValue());
        //设置业务参数，bizContent为发送的请求信息，开发者需要根据实际情况填充此类
        Object obj = null;
        try {
            obj = new ObjectMapper().writeValueAsString(params);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        alipayRequest.setBizContent(obj.toString());
        //sdk请求客户端，已将配置信息初始化
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeRefundResponse alipayResponse = null;
        try {
            alipayResponse = alipayClient.execute(alipayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return alipayResponse;
    }

    /**
     * 轮询获取当前订单状态
     *
     * @param oid 订单id
     * @return 订单状态
     */
    public ServerResponse<AlipayTradeQueryResponse> alipayTradeQueryService(String oid) {
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        Map<String, Object> params = new HashMap<>();
        params.put("out_trade_no", oid);
        //设置业务参数，bizContent为发送的请求信息，开发者需要根据实际情况填充此类
        try {
            alipayRequest.setBizContent(new ObjectMapper().writeValueAsString(params));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //sdk请求客户端，已将配置信息初始化
        AlipayClient alipayClient = AliService.getAlipayClient();
        AlipayTradeQueryResponse alipayResponse = null;
        try {
            //因为是接口服务，使用exexcute方法获取到返回值
            alipayResponse = alipayClient.execute(alipayRequest);
            if (alipayResponse.isSuccess()) {
                alipayResponse.getTradeStatus();
                // 支付成功更新订单状态
                if (alipayResponse.getTradeStatus().equals("TRADE_SUCCESS")) {
                    Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("oid", oid));
                    order.setState(OrderState.ACCOUNT_PAID.getCode());
                    orderMapper.updateById(order);
                }
                logger.info("调用成功");
            } else {
                logger.info("调用失败");
            }
            return ServerResponse.createSuccessData("", alipayResponse);
        } catch (AlipayApiException e) {
            if (e.getCause() instanceof java.security.spec.InvalidKeySpecException) {
                return ServerResponse.createErrorMessage("商户私钥格式不正确，请确认配置文件alipay_openapi_sanbox.properties中是否配置正确");
            }
        }
        return ServerResponse.createSuccessData("", alipayResponse);
    }

    public static AlipayClient getAlipayClient() {
        ResourceBundle bundle = ResourceBundle.getBundle("alipay_openapi_sanbox");
        // 网关
        String URL = bundle.getString("ALIPAY_GATEWAY_URL");
        // 商户APP_ID
        String APP_ID = bundle.getString("APP_ID");
        // 商户RSA 私钥
        String APP_PRIVATE_KEY = bundle.getString("RSA2_PRIVATE_KEY");
        // 请求方式 json
        String FORMAT = bundle.getString("FORMAT");
        // 编码格式，目前只支持UTF-8
        String CHARSET = bundle.getString("CHARSET");
        // 支付宝公钥
        String ALIPAY_PUBLIC_KEY = bundle.getString("ALIPAY_RSA2_PUBLIC_KEY");
        // 签名方式
        String SIGN_TYPE = bundle.getString("SIGN_TYPE");
        return new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
    }
}
